package servlets;

import db.ExpenseDAO;
import beans.ExpenseBean;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;

@WebServlet("/ExportExpenseServlet")
public class ExportExpenseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        int expenseId = Integer.parseInt(request.getParameter("id"));

        ExpenseDAO dao = new ExpenseDAO();
        try {
            ExpenseBean record = dao.getExpenseById(expenseId);

            if (record != null) {
                // 设置响应内容类型为Excel
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment; filename=expense_" + expenseId + ".xls");

                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

                // 生成Excel内容
                StringBuilder sb = new StringBuilder();
                sb.append("用车费用报销单\n\n");
                sb.append("单号:\t").append(record.getExpenseId()).append("\n");
                sb.append("卡号:\t").append(record.getCardNumber()).append("\n");
                sb.append("类型:\t").append(record.getType()).append("\n");
                sb.append("描述:\t").append(record.getDescription()).append("\n");
                sb.append("金额:\t").append(record.getAmount()).append("\n");
                sb.append("日期:\t").append(dateFormat.format(record.getDate())).append("\n");
                sb.append("状态:\t").append(record.getApprovedBy() > 0 ? "已审批" : "待审批").append("\n");
                sb.append("审批人:\t").append(record.getApproverName()).append("\n");

                response.getWriter().write(sb.toString());
            } else {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "未找到指定的报销记录");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "数据库错误: " + e.getMessage());
        }
    }
}